﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MappingGenerator.Template;

namespace MappingGenerator
{
    public class FileOutPut
    {
        public string SavePath { get; set; }
        public FileOutPut()
        {
            SavePath = "C:\\temp";
        }
        public void WriteFile(string fileName,string text)
        {
           EnsurePath(SavePath);
           WriteFileInternal(Path.Combine(Path.Combine(SavePath, fileName), fileName), text);
        }
        public void WriteFile(string subDirectoryPath,string fileName, string text)
        {
            var dirPath = Path.Combine(SavePath, subDirectoryPath);
            EnsurePath(dirPath);
            WriteFileInternal(Path.Combine(dirPath, fileName),text);
        }
        public void WriteFileInternal(string path, string text)
        {
            using (var stream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(text);
                    writer.Flush();
                    writer.Close();
                }
            }
        }

        private void EnsurePath(string folderPath)
        {
            if(!Directory.Exists(folderPath))
            Directory.CreateDirectory(folderPath);
        }
        public void Render(MappingTemplate template)
        {
            
            WriteFile(template.Namespace, template.EntityName() + "Map.cs",template.TransformText());
        }
        public void Render(EntityTemplate template)
        {
            WriteFile(template.Namespace, template.EntityName() + ".cs", template.TransformText());
        }
        public void Render(MappingBaseTemplate template)
        {
            WriteFile(template.Namespace, "EntityMap.cs", template.TransformText());
        }
    }
}
